package com.example.admanagement;

import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AdService {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AdService.class);

    // 从数据库查询所有广告信息的方法，返回结果封装在Result对象中，便于传递状态和数据
    public static Result<List<Ad>> getAdsFromDatabase() {
        List<Ad> ads = new ArrayList<>();
        Connection connection = DBUtil.getConnection();
        if (connection == null) {
            return new Result<>(false, "数据库连接失败，无法获取广告数据", null);
        }
        String sql = "SELECT * FROM ads_table";
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql);
             ResultSet resultSet = preparedStatement.executeQuery()) {
            while (resultSet.next()) {
                Ad ad = new Ad();
                ad.setId(resultSet.getInt("id"));
                ad.setImagePath(resultSet.getString("image_path"));
                ad.setLink(resultSet.getString("link"));
                ad.setTitle(resultSet.getString("title"));
                ad.setDescription(resultSet.getString("description"));
                ads.add(ad);
            }
            return new Result<>(true, "广告数据获取成功", ads);
        } catch (SQLException e) {
            logger.error("获取广告数据时出现数据库操作异常", e);
            return new Result<>(false, "获取广告数据失败：" + e.getMessage(), null);
        }
    }

    // 向数据库插入新广告信息的方法，返回插入操作的结果封装在Result对象中
    public static Result<Void> insertAd(Ad ad) {
        Connection connection = DBUtil.getConnection();
        if (connection == null) {
            return new Result<>(false, "数据库连接失败，无法插入广告数据", null);
        }
        String sql = "INSERT INTO ads_table (image_path, link, title, description) VALUES (?,?,?,?)";
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setString(1, ad.getImagePath());
            preparedStatement.setString(2, ad.getLink());
            preparedStatement.setString(3, ad.getTitle());
            preparedStatement.setString(4, ad.getDescription());
            preparedStatement.executeUpdate();
            return new Result<>(true, "广告数据插入成功", null);
        } catch (SQLException e) {
            logger.error("插入广告数据时出现数据库操作异常", e);
            return new Result<>(false, "插入广告数据失败：" + e.getMessage(), null);
        }
    }

    // 根据广告ID更新广告信息的方法，返回更新操作的结果封装在Result对象中
    public static Result<Void> updateAd(Ad ad) {
        Connection connection = DBUtil.getConnection();
        if (connection == null) {
            return new Result<>(false, "数据库连接失败，无法更新广告数据", null);
        }
        String sql = "UPDATE ads_table SET image_path=?, link=?, title=?, description=? WHERE id=?";
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setString(1, ad.getImagePath());
            preparedStatement.setString(2, ad.getLink());
            preparedStatement.setString(3, ad.getTitle());
            preparedStatement.setString(4, ad.getDescription());
            preparedStatement.setInt(5, ad.getId());
            preparedStatement.executeUpdate();
            return new Result<>(true, "广告数据更新成功", null);
        } catch (SQLException e) {
            logger.error("更新广告数据时出现数据库操作异常", e);
            return new Result<>(false, "更新广告数据失败：" + e.getMessage(), null);
        }
    }

    // 根据广告ID删除广告信息的方法，返回删除操作的结果封装在Result对象中
    public static Result<Void> deleteAd(String id) {
        Connection connection = DBUtil.getConnection();
        if (connection == null) {
            return new Result<>(false, "数据库连接失败，无法删除广告数据", null);
        }
        String sql = "DELETE FROM ads_table WHERE id=?";
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setInt(1, Integer.parseInt(id));
            preparedStatement.executeUpdate();
            return new Result<>(true, "广告数据删除成功", null);
        } catch (SQLException e) {
            logger.error("删除广告数据时出现数据库操作异常", e);
            return new Result<>(false, "删除广告数据失败：" + e.getMessage(), null);
        }
    }

    // 自定义的结果封装类，用于传递操作结果状态、消息以及对应的数据（泛型类型表示数据类型）
    public static class Result<T> {
        private boolean success;
        private String message;
        private T data;

        public Result(boolean success, String message, T data) {
            this.success = success;
            this.message = message;
            this.data = data;
        }

        public boolean isSuccess() {
            return success;
        }

        public String getMessage() {
            return message;
        }

        public T getData() {
            return data;
        }
    }
}